<template>
  <div class="body-box cert-bodys">
    <el-row :gutter="20">
      <el-col :span="6">
        <window-title title="字段列表"></window-title>
        <div class="result-name-list">
          <div
            @click="selectLabel(key)"
            v-for="(item,key) in result_name"
            :key="key"
            :class="checkInArr(item.name,select_lable) ? 'active' : ''"
          >{{item.name}}</div>
        </div>
        <div v-if="select_index >= 0">
          <window-title title="字段样式"></window-title>
          <div>
            <el-form label-position="top" size="mini">
              <el-form-item label="文字大小">
                <el-select v-model="select_lable[select_index].fontSize" @change="changeSize">
                  <el-option
                    v-for="(item,key) in font_size"
                    :key="key"
                    :value="item"
                    :label="item+'px'"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="文字颜色">
                <el-color-picker v-model="select_lable[select_index].color"></el-color-picker>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div>
          <window-title title="证书操作"></window-title>
          <el-button style="margin-top:20px;" class="com-btn" @click="saveCert()">保存证书</el-button>
        </div>
      </el-col>
      <el-col :span="18">
        <div class="cert-up-body">
          <window-title title="证书设置"></window-title>
          <div class="cert-up-btn">
            <i class="el-icon-upload2"></i>
            <span>上传证书封面</span>
            <input type="file" class="cart-up-file" @change="upCover($event)" />
          </div>
        </div>
        <div class="cert-img-box" v-if="!img_url">证书封面</div>
        <div
          class="cert-img-bodys"
          ref="cart_cover"
          v-else
          @mousemove="moveLabel"
          @mouseup="labelUp"
          
        >
          <img :src="$oss_url + img_url" alt="证书封面" ref="certcover" class="cert-img-src" draggable="false" />
          <span
            :class="moveClass(key)"
            v-for="(item,key) in select_lable"
            :key="key"
            :style="'top:'+item.dY+'px;left:'+item.dX+'px;font-size:'+item.fontSize+'px;color:'+item.color"
            @mousedown.stop="lableDown($event,key)"
          >
            {{item.name}}
            <i class="el-icon-close"  @mousedown.stop="deleteLabel(key)"></i>
          </span>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import windowTitle from "../../../components/unit/title.vue";

export default {
  props: { result_name: {} ,team_id : {} , select_arr : {} , active_id:{} , img_cover:{}},
  components: { windowTitle },
  data() {
    return {
      //   img_url: "/active/cover/2019/11/4/13_52_15_173.png",
      img_url: "",
      temp_data: {},
      temp_x: 0,
      temp_y: 0,
      cert_label_index: -1,
      select_lable: [],
      select_index: -1,
      allow_move: false,
      font_size: [12, 13, 14, 15, 16, 17, 18,19,20,21,22],
      ox:0,
      oy:0
    };
  },
  mounted(){
    this. select_lable = this.select_arr;
    this.img_url = this.img_cover;
  },
  methods: {
    //设置类
    moveClass(key){
      var class_name = '';
      if(this.select_index == key) {
        class_name =  'cert-bodys-label active';
      }else {
        class_name = 'cert-bodys-label';
      }
      if(this.allow_move){
        class_name = class_name + ' child-select';
      }
      return class_name;
    },
    /**
     * 选中报名项
     */
    selectLabel(key) {
      if(!this.img_url)return this.toast(0,'请先上传证书封面');
      if (!this.checkInArr(this.result_name[key].name, this.select_lable)) {
        var item = this.result_name[key];
        item.fontSize = "12";
        item.color = "#333";
        item.dY = 100;
        item.dX = 100;
        this.select_lable.push(item);
      }
    },
    /**
     * 删除报名项
     */
    deleteLabel(key) {
      console.log(1);
      this.select_index = this.select_lable.length > 1 ? 0 : -1;
      this.select_lable.splice(key, 1);
    },
    //选中字段
    lableDown(e,key) {
      this.ox = e.offsetX;
      this.oy = e.offsetY;
      this.select_index = key;
      this.allow_move = true;
    },
    //移除选中字段
    labelUp() {
      this.allow_move = false;
    },
    //移动字段
    moveLabel(e) {
      if (this.allow_move) {
        this.select_lable[this.select_index].dY = e.offsetY - this.oy;
        this.select_lable[this.select_index].dX = e.offsetX - this.ox;
      }
    },
    //改变字体大小
    changeSize(e) {
    },
    //检测字符串是否在数组中
    checkInArr(str, arr) {
      for (var i in arr) {
        if (arr[i].name == str) {
          return true;
        }
      }
      return false;
    },
    //上传证书背景
    upCover(e) {
      var file = e.currentTarget;
      var img = file.files[0];

      if (img == undefined) return false;
      //获取文件后缀名
      var arr = img["name"].split(".");
      var img_type = arr[1];
      //验证图片格式
      if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(img.name)) {
        this.$message.error("请上传正确格式的图片");
        return false;
      }
      var kb = 1024; //1KB字节数
      var mb = 1025 * 1024; //1mb字节数
      //验证图片大小
      if (img.size > 4 * mb) {
        this.$message.error("图片大小不能超过4M");
        return false;
      }

      var reader = new FileReader();
      reader.onload = evt => {
        //this.img_src = evt.target.result;
        // this.$emit('change',this.img_src);
        let OSS = require("ali-oss");
        let client = new OSS({
          region: "oss-cn-hangzhou",
          //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，部署在服务端使用RAM子账号或STS，部署在客户端使用STS。
          accessKeyId: "LTAIWdxCuPiIzLfm",
          accessKeySecret: "z1zLih5CgWNkWfuzHj7SbpJKVdME2a",
          bucket: "ykp-new"
        });
        // client.options.endpoint.protocol = "https:";
        //获取当前时间
        var date = new Date();
        var file_name =
          date.getFullYear() +
          "/" +
          (date.getMonth() + 1) +
          "/" +
          date.getDate() +
          "/" +
          date.getHours() +
          "_" +
          date.getMinutes() +
          "_" +
          date.getSeconds() +
          "_" +
          date.getMilliseconds();
        let filename = "/active/cover/" + file_name + "." + img_type;
        let res_file = this.dataURLtoFile(evt.target.result, "");
        let that = this;
        async function put() {
          try {
            //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
            let result = await client
              .multipartUpload(filename, res_file, {
                progress: percentage => {}
              })
              .then(res => {
                that.img_url = res.name;
                //console.log(res);
              })
              .catch(err => {
                return that.toast(0, "上传失败");
              });
          } catch (e) {
            return that.toast(0, "上传失败");
          }
        }
        put();
      };
      reader.readAsDataURL(file.files[0]);
    },
    /**
     * base64转文件
     */
    dataURLtoFile(dataurl, filename) {
      let arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    /**
     * 保存证书与
     */
    saveCert() {
      var box = this.$refs.certcover;
      if (this.select_lable.length == 0) return this.toast(0, "字段不能少于1");
      if (!this.img_url) return this.toast(0, "请上传证书封面");
      for(var i in this.select_lable) {
        this.select_lable[i].px = box.width;
        this.select_lable[i].py = box.height;
      }
      this.ajaxs('Activematch/saveModel',{
        data:{active_id : this.active_id , team_id : this.team_id , select_form : this.select_lable , img_url : this.img_url},
        success:(res) => {
          this.toast(res.code,res.msg);
          if(res.code){
            this.$parent.getMatchHead();
          }
        }
      });
    }
  }
};
</script>

<style>
.child-select{
  pointer-events: none;
}
.cert-img-bodys .active {
  /* background: #fff; */
  border: 1px solid #333;
  
}
.cert-bodys-label {
  position: absolute;
  z-index: 99999;
  top: 0;
  left: 0;
  cursor: move;
  padding: 5px 15px;
  /* border: 1px dashed #333; */
  border-radius: 2px;
}
.cert-bodys-label i {
  cursor: pointer;
}
.cert-bodys-label i:hover {
  background: #eee;
}
.temp_show {
  position: absolute;
  z-index: 9999999;
  background: #eee;
}
.cert-bodys {
  overflow-y: auto;
}
.result-name-list {
  overflow: hidden;
  margin-bottom: 10px;
}
.result-name-list > div {
  float: left;
  padding: 3px 15px;
  margin-right: 10px;
  margin-top: 10px;
  border: 1px solid #e1e1e1;
  border-radius: 3px;
  cursor: pointer;
}
.result-name-list .active {
  background: #8a70c6;
  color: #fff;
  border-color: #8a70c6;
}
.cert-up-body {
  position: relative;
}
.cert-up-btn {
  width: 140px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background: #8a70c6;
  color: #fff;
  border-radius: 3px;
  cursor: pointer;
  position: absolute;
  right: 0;
  bottom: 10px;
}
.cert-up-btn > span {
  margin-left: 5px;
}
.cart-up-file {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  cursor: pointer;
  opacity: 0;
}
.cert-img-box {
  width: 80%;
  margin: auto;
  background: #e3ecfb;
  height: 400px;
  margin-top: 20px;
  text-align: center;
  line-height: 400px;
  color: #999;
}
.cert-img-bodys {
  width: 80%;
  margin: 20px auto;
  position: relative;
  overflow: hidden;
  z-index: 99;
}
.cert-img-src {
  width: 100%;
}
</style>